home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / editors / emcs1857 / 1857el~1.zoo / lisp / sort.el < prev    next >
Encoding:
Text File  |  1992-02-04  |  12.8 KB  |  349 lines

  1. ;; Commands to sort text in an Emacs buffer.
  2. ;; Copyright (C) 1986, 1987, 1990 Free Software Foundation, Inc.
  3.  
  4. ;; This file is part of GNU Emacs.
  5.  
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation; either version 1, or (at your option)
  9. ;; any later version.
  10.  
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ;; GNU General Public License for more details.
  15.  
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  18. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. (provide 'sort)
  21.  
  22. ;; Original version of most of this contributed by Howie Kaye
  23.  
  24.  
  25. ;; Modified 1990 for 8-bit character support by Howard Gayle.
  26. ;; See case-table.el for details.
  27.  
  28. (defun sort-subr (reverse nextrecfun endrecfun &optional startkeyfun endkeyfun)
  29.   "General text sorting routine to divide buffer into records and sort them.
  30. Arguments are REVERSE NEXTRECFUN ENDRECFUN &optional STARTKEYFUN ENDKEYFUN.
  31.  
  32. We consider this portion of the buffer to be divided into disjoint pieces
  33. called sort records.  A portion of each sort record (perhaps all of it)
  34. is designated as the sort key.  The records are rearranged in the buffer
  35. in order by their sort keys.  The records may or may not be contiguous.
  36.  
  37. Usually the records are rearranged in order of ascending sort key.
  38. If REVERSE is non-nil, they are rearranged in order of descending sort key.
  39.  
  40. The next four arguments are functions to be called to move point
  41. across a sort record.  They will be called many times from within sort-subr.
  42.  
  43. NEXTRECFUN is called with point at the end of the previous record.
  44. It moves point to the start of the next record.
  45. The first record is assumed to start at the position of point when sort-subr
  46. is called.
  47.  
  48. ENDRECFUN is is called with point within the record.
  49. It should move point to the end of the record.
  50.  
  51. STARTKEYFUN may moves from the start of the record to the start of the key.
  52. It may return either return a non-nil value to be used as the key, or
  53. else the key will be the substring between the values of point after
  54. STARTKEYFUN and ENDKEYFUN are called.  If STARTKEYFUN is nil, the key
  55. starts at the beginning of the record.
  56.  
  57. ENDKEYFUN moves from the start of the sort key to the end of the sort key.
  58. ENDRECFUN may be nil if STARTKEYFUN returns a value or if it would be the
  59. same as ENDRECFUN."
  60.   (save-excursion
  61.     (message "Finding sort keys...")
  62.     (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
  63.                     startkeyfun endkeyfun))
  64.        (old (reverse sort-lists)))
  65.       (if (null sort-lists)
  66.       ()
  67.     (or reverse (setq sort-lists (nreverse sort-lists)))
  68.     (message "Sorting records...")
  69.     (setq sort-lists
  70.           (if (fboundp 'sortcar)
  71.           (sortcar sort-lists
  72.                (cond ((numberp (car (car sort-lists)))
  73.                   '<)
  74.                  ((consp (car (car sort-lists)))
  75.                   'buffer-substring-lessp)
  76.                  (t
  77.                   'string-lessp*)))
  78.           (sort sort-lists
  79.             (cond ((numberp (car (car sort-lists)))
  80.                    (function
  81.                 (lambda (a b)
  82.                   (< (car a) (car b)))))
  83.                   ((consp (car (car sort-lists)))
  84.                    (function
  85.                 (lambda (a b)
  86.                   (buffer-substring-lessp (car a) (car b)))))
  87.                   (t
  88.                    (function
  89.                 (lambda (a b)
  90.                   (string-lessp* (car a) (car b)))))))))
  91.     (if reverse (setq sort-lists (nreverse sort-lists)))
  92.     (message "Reordering buffer...")
  93.     (sort-reorder-buffer sort-lists old)))
  94.     (message "Reordering buffer... Done")))
  95.  
  96. ;; Parse buffer into records using the arguments as Lisp expressions;
  97. ;; return a list of records.  Each record looks like (KEY STARTPOS ENDPOS)
  98. ;; where KEY is the sort key (a number or string),
  99. ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
  100.  
  101. ;; The records appear in the list lastmost first!
  102.  
  103. (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
  104.   (let ((sort-lists ())
  105.     (start-rec nil)
  106.     done key)
  107.     ;; Loop over sort records.
  108.     ;(goto-char (point-min)) -- it is the caller's responsibility to
  109.     ;arrange this if necessary
  110.     (while (not (eobp))
  111.       (setq start-rec (point))        ;save record start
  112.       (setq done nil)
  113.       ;; Get key value, or move to start of key.
  114.       (setq key (catch 'key
  115.           (or (and startkeyfun (funcall startkeyfun))
  116.               ;; If key was not returned as value,
  117.               ;; move to end of key and get key from the buffer.
  118.               (let ((start (point)))
  119.             (funcall (or endkeyfun
  120.                      (prog1 endrecfun (setq done t))))
  121.             (if (fboundp 'buffer-substring-lessp)
  122.                 (cons start (point))
  123.               (buffer-substring start (point)))))))
  124.       ;; Move to end of this record (start of next one, or end of buffer).
  125.       (cond ((prog1 done (setq done nil)))
  126.         (endrecfun (funcall endrecfun))
  127.         (nextrecfun (funcall nextrecfun) (setq done t)))
  128.       (if key (setq sort-lists (cons
  129.                  ;; consing optimization in case in which key
  130.                  ;; is same as record.
  131.                  (if (and (consp key)
  132.                       (equal (car key) start-rec)
  133.                       (equal (cdr key) (point)))
  134.                      (cons key key)
  135.                      (list key start-rec (point)))
  136.                 sort-lists)))
  137.       (and (not done) nextrecfun (funcall nextrecfun)))
  138.     sort-lists))
  139.  
  140. (defun sort-reorder-buffer (sort-lists old)
  141.   (let ((inhibit-quit t)
  142.     (last (point-min))
  143.     (min (point-min)) (max (point-max)))
  144.     (while sort-lists
  145.       (goto-char (point-max))
  146.       (insert-buffer-substring (current-buffer)
  147.                    last
  148.                    (nth 1 (car old)))
  149.       (goto-char (point-max))
  150.       (insert-buffer-substring (current-buffer)
  151.                    (nth 1 (car sort-lists))
  152.                    (nth 2 (car sort-lists)))
  153.       (setq last (nth 2 (car old))
  154.         sort-lists (cdr sort-lists)
  155.         old (cdr old)))
  156.     (goto-char (point-max))
  157.     (insert-buffer-substring (current-buffer)
  158.                  last
  159.                  max)
  160.     (delete-region min max)))    ;get rid of old version
  161.  
  162. (defun sort-lines (reverse beg end) 
  163.   "Sort lines in region alphabetically; argument means descending order.
  164. Called from a program, there are three arguments:
  165. REVERSE (non-nil means reverse order), BEG and END (region to sort)."
  166.   (interactive "P\nr")
  167.   (save-restriction
  168.     (narrow-to-region beg end)
  169.     (goto-char (point-min))
  170.     (sort-subr reverse 'forward-line 'end-of-line)))
  171.  
  172. (defun sort-paragraphs (reverse beg end)
  173.   "Sort paragraphs in region alphabetically; argument means descending order.
  174. Called from a program, there are three arguments:
  175. REVERSE (non-nil means reverse order), BEG and END (region to sort)."
  176.   (interactive "P\nr")
  177.   (save-restriction
  178.     (narrow-to-region beg end)
  179.     (goto-char (point-min))
  180.     (sort-subr reverse
  181.            (function (lambda () (skip-chars-forward "\n \t\f")))
  182.            'forward-paragraph)))
  183.  
  184. (defun sort-pages (reverse beg end)
  185.   "Sort pages in region alphabetically; argument means descending order.
  186. Called from a program, there are three arguments:
  187. REVERSE (non-nil means reverse order), BEG and END (region to sort)."
  188.   (interactive "P\nr")
  189.   (save-restriction
  190.     (narrow-to-region beg end)
  191.     (goto-char (point-min))
  192.     (sort-subr reverse
  193.            (function (lambda () (skip-chars-forward "\n")))
  194.            'forward-page)))
  195.  
  196. (defvar sort-fields-syntax-table nil)
  197. (if sort-fields-syntax-table nil
  198.   (let ((table (make-syntax-table))
  199.     (i 0))
  200.     (while (< i 256)
  201.       (modify-syntax-entry i "w" table)
  202.       (setq i (1+ i)))
  203.     (modify-syntax-entry ?\  " " table)
  204.     (modify-syntax-entry ?\t " " table)
  205.     (modify-syntax-entry ?\n " " table)
  206.     (setq sort-fields-syntax-table table)))
  207.  
  208. (defun sort-numeric-fields (field beg end)
  209.   "Sort lines in region numerically by the ARGth field of each line.
  210. Fields are separated by whitespace and numbered from 1 up.
  211. Specified field must contain a number in each line of the region.
  212. With a negative arg, sorts by the -ARG'th field, in reverse order.
  213. Called from a program, there are three arguments:
  214. FIELD, BEG and END.  BEG and END specify region to sort."
  215.   (interactive "p\nr")
  216.   (sort-fields-1 field beg end
  217.          (function (lambda ()
  218.                  (sort-skip-fields (1- field))
  219.                  (string-to-int
  220.                   (buffer-substring
  221.                     (point)
  222.                 (save-excursion
  223.                   (skip-chars-forward "-0-9")
  224.                   (point))))))
  225.          nil))
  226.  
  227. (defun sort-fields (field beg end)
  228.   "Sort lines in region lexicographically by the ARGth field of each line.
  229. Fields are separated by whitespace and numbered from 1 up.
  230. With a negative arg, sorts by the -ARG'th field, in reverse order.
  231. Called from a program, there are three arguments:
  232. FIELD, BEG and END.  BEG and END specify region to sort."
  233.   (interactive "p\nr")
  234.   (sort-fields-1 field beg end
  235.          (function (lambda ()
  236.                  (sort-skip-fields (1- field))
  237.                  nil))
  238.          (function (lambda () (skip-chars-forward "^ \t\n")))))
  239.  
  240. (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
  241.   (let ((reverse (< field 0))
  242.     (tbl (syntax-table)))
  243.     (setq field (max 1 field (- field)))
  244.     (unwind-protect
  245.     (save-restriction
  246.       (narrow-to-region beg end)
  247.       (goto-char (point-min))
  248.       (set-syntax-table sort-fields-syntax-table)
  249.       (sort-subr reverse
  250.              'forward-line 'end-of-line
  251.              startkeyfun endkeyfun))
  252.       (set-syntax-table tbl))))
  253.  
  254. (defun sort-skip-fields (n)
  255.   (let ((eol (save-excursion (end-of-line 1) (point))))
  256.     (forward-word n)
  257.     (if (> (point) eol)
  258.     (error "Line has too few fields: %s"
  259.            (buffer-substring (save-excursion
  260.                    (beginning-of-line) (point))
  261.                  eol)))
  262.     (skip-chars-forward " \t")))
  263.  
  264.  
  265. (defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
  266.   "Sort the region lexicographically as specifed by RECORD-REGEXP and KEY.
  267. RECORD-REGEXP specifies the textual units which should be sorted.
  268.   For example, to sort lines RECORD-REGEXP would be \"^.*$\"
  269. KEY specifies the part of each record (ie each match for RECORD-REGEXP)
  270.   is to be used for sorting.
  271.   If it is \"\\digit\" then the digit'th \"\\(...\\)\" match field from
  272.   RECORD-REGEXP is used.
  273.   If it is \"\\&\" then the whole record is used.
  274.   Otherwise, it is a regular-expression for which to search within the record.
  275. If a match for KEY is not found within a record then that record is ignored.
  276.  
  277. With a negative prefix arg sorts in reverse order.
  278.  
  279. For example: to sort lines in the region by the first word on each line
  280.  starting with the letter \"f\",
  281.  RECORD-REGEXP would be \"^.*$\" and KEY \"\\<f\\w*\\>\""
  282.   (interactive "P\nsRegexp specifying records to sort: 
  283. sRegexp specifying key within record: \nr")
  284.   (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
  285.      (setq key-regexp 0))
  286.     ((string-match "\\`\\\\[1-9]\\'" key-regexp)
  287.      (setq key-regexp (- (aref key-regexp 1) ?0))))
  288.   (save-restriction
  289.     (narrow-to-region beg end)
  290.     (goto-char (point-min))
  291.     (let (sort-regexp-record-end) ;isn't dynamic scoping wonderful?
  292.       (re-search-forward record-regexp)
  293.       (setq sort-regexp-record-end (point))
  294.       (goto-char (match-beginning 0))
  295.       (sort-subr reverse
  296.          (function (lambda ()
  297.                  (and (re-search-forward record-regexp nil 'move)
  298.                   (setq sort-regexp-record-end (match-end 0))
  299.                   (goto-char (match-beginning 0)))))
  300.          (function (lambda ()
  301.                  (goto-char sort-regexp-record-end)))
  302.          (function (lambda ()
  303.                  (let ((n 0))
  304.                    (cond ((numberp key-regexp)
  305.                       (setq n key-regexp))
  306.                      ((re-search-forward
  307.                         key-regexp sort-regexp-record-end t)
  308.                       (setq n 0))
  309.                      (t (throw 'key nil)))
  310.                    (condition-case ()
  311.                    (if (fboundp 'buffer-substring-lessp)
  312.                        (cons (match-beginning n)
  313.                          (match-end n))
  314.                        (buffer-substring (match-beginning n)
  315.                              (match-end n)))
  316.                  ;; if there was no such register
  317.                  (error (throw 'key nil))))))))))
  318.  
  319.  
  320. (defun sort-columns (reverse &optional beg end)
  321.   "Sort lines in region alphabetically by a certain range of columns.
  322. For the purpose of this command, the region includes
  323. the entire line that point is in and the entire line the mark is in.
  324. The column positions of point and mark bound the range of columns to sort on.
  325. A prefix argument means sort into reverse order.
  326.  
  327. Note that sort-columns uses the sort utility program and therefore
  328. cannot work on text containing TAB characters.  Use M-x untabify
  329. to convert tabs to spaces before sorting."
  330.   (interactive "P\nr")
  331.   (save-excursion
  332.     (let (beg1 end1 col-beg1 col-end1 col-start col-end)
  333.       (goto-char (min beg end))
  334.       (setq col-beg1 (current-column))
  335.       (beginning-of-line)
  336.       (setq beg1 (point))
  337.       (goto-char (max beg end))
  338.       (setq col-end1 (current-column))
  339.       (forward-line)
  340.       (setq end1 (point))
  341.       (setq col-start (min col-beg1 col-end1))
  342.       (setq col-end (max col-beg1 col-end1))
  343.       (if (search-backward "\t" beg1 t)
  344.       (error "sort-columns does not work with tabs.  Use M-x untabify."))
  345.       (call-process-region beg1 end1 "sort" t t nil
  346.                (if reverse "-rt\n" "-t\n")
  347.                            (concat "+0." col-start)
  348.                            (concat "-0." col-end)))))
  349.